package com.zbl.zblproject.other.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.zbl.zblproject.core.entity.Brand;
import com.zbl.zblproject.core.entity.Result;
import com.zbl.zblproject.core.entity.SmallUnit;
import com.zbl.zblproject.core.entity.Supplier;
import com.zbl.zblproject.core.mapper.BrandMapper;
import com.zbl.zblproject.core.mapper.OrderItemMapper;
import com.zbl.zblproject.core.mapper.SmallUnitMapper;
import com.zbl.zblproject.core.mapper.SupplierMapper;
import com.zbl.zblproject.core.utils.ResultUtil;
import com.zbl.zblproject.core.utils.StringUtil;
import com.zbl.zblproject.erp.entity.*;
import com.zbl.zblproject.erp.mapper.*;
import com.zbl.zblproject.other.entity.GoodsItem;
import com.zbl.zblproject.other.mapper.GoodsItemMapper;
import com.zbl.zblproject.other.service.UtilService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author youlanqiang
 * @version 1.0
 * @date 2018/11/14
 */
@Service
@Transactional
public class UtilServiceImpl implements UtilService {


    @Autowired
    private ErpGoodMapper erpGoodMapper;

    @Autowired
    private SmallUnitMapper smallUnitMapper;

    @Autowired
    private ErpCategoryMapper erpCategoryMapper;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private SupplierMapper supplierMapper;


    @Autowired
    ErpOrderItemMapper erpOrderItemMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    ErpOrderMapper erpOrderMapper;

    @Autowired
    ErpOweGoodsItemMapper erpOweGoodsItemMapper;

    @Autowired
    ErpWarehouseItemMapper erpWarehouseItemMapper;

    @Autowired
    GoodsItemMapper goodsItemMapper;


    @Override
    public void updateErpOrder() {
        List<ErpOrder> list = erpOrderMapper.selectList(null);
        for (ErpOrder order : list) {
            List<ErpOrderItem> items = erpOrderItemMapper.selectOrderItemsByOrderId(order.getOrderId());
            String brandName = Joiner.on(',').skipNulls().join(getItemsBrandName(items));
            order.setBrandName(brandName);
           // order.setSupplierName(supplierMapper.selectSupplierNameByGoodsId(id));
            erpOrderMapper.updateById(order);
        }
    }

    private Set<String> getItemsBrandName(List<ErpOrderItem> items){
        if(items == null){
            throw new NullPointerException("items is null");
        }
        Set<String> brands = new HashSet<>();
        for(ErpOrderItem item : items){
            brands.add(brandMapper.selectBrandNameByGoodsId(item.getGoodsId()));
        }
        return brands;
    }

    @Override
    public void cancelErpOrder(String orderSn) {
        ErpOrder outOrder = erpOrderMapper.selectErpOrderByOrderSn(orderSn);
        Preconditions.checkNotNull(outOrder, "没有发现对应的订单号");
        if (outOrder.getMode() == 1) {
            List<ErpOrderItem> orderItems = erpOrderItemMapper.selectOrderItemsByOrderId(outOrder.getOrderId());
            for (ErpOrderItem orderItem : orderItems) {
                ErpGoods goods = erpGoodMapper.selectById(orderItem.getGoodsId());
                goods.setGoodsNumber(goods.getGoodsNumber() + orderItem.getGoodsNum());
                erpGoodMapper.updateById(goods);
                ErpWarehouseItem item = erpWarehouseItemMapper.selectItemByGoodsIdAndWhId(goods.getGoodsId(), orderItem.getGoodsList());
                item.setStock(item.getStock() + orderItem.getGoodsNum());
                erpWarehouseItemMapper.updateById(item);
                if (orderItem.getOweNum() > 0) {
                    erpOweGoodsItemMapper.deleteByErpItemId(orderItem.getId());
                }
            }
            outOrder.setStatus(1);
            erpOrderMapper.deleteById(outOrder.getOrderId());
        } else {
            throw new RuntimeException("暂时不支持入库!");
        }
    }

    @Override
    public boolean updateGoodsItemToDatabase(MultipartFile file) {
        try {

            Workbook workbook = null;
            if (StringUtil.getFileSuffix(file.getOriginalFilename()).equals("xls")) {
                workbook = new HSSFWorkbook(file.getInputStream());
            } else if (StringUtil.getFileSuffix(file.getOriginalFilename()).equals("xlsx")) {
                workbook = new XSSFWorkbook(file.getInputStream());
            } else {
                throw new RuntimeException("错误的文件类型");
            }
            Sheet sheet = workbook.getSheetAt(0);
            if (sheet == null) {
                return false;
            }
            Row row;
            for (int r = 1; r <= sheet.getLastRowNum(); r++) {
                row = sheet.getRow(r);
                if (row == null || row.getCell(0) == null) {
                    continue;
                }
                //分类名称
                String goodsSn = getCellString(row, 0);
                //条码
                String goodsName = getCellString(row, 1);
                //商品名称
                GoodsItem item = new GoodsItem();

                item.setGoodsSn(goodsSn);
                item.setGoodsName(goodsName);
                item.setStoreName(file.getOriginalFilename());
                goodsItemMapper.insert(item);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("excel文件读取错误!");
        }
        return true;

    }

    @Override
    public Result updateGoodsToDatabase(MultipartFile file) {
        try {

            Workbook workbook = null;
            if (StringUtil.getFileSuffix(file.getOriginalFilename()).equals("xls")) {
                workbook = new HSSFWorkbook(file.getInputStream());
            } else if (StringUtil.getFileSuffix(file.getOriginalFilename()).equals("xlsx")) {
                workbook = new XSSFWorkbook(file.getInputStream());
            } else {
                return ResultUtil.error("错误的文件类型");
            }
            Sheet sheet = workbook.getSheetAt(0);
            if (sheet == null) {
                return ResultUtil.error("excel表格为空");
            }
            Row row;
            for (int r = 1; r <= sheet.getLastRowNum(); r++) {
                row = sheet.getRow(r);
                if (row == null || row.getCell(0) == null) {
                    continue;
                }
                //分类名称
                String catId = getCellString(row, 0);
                //条码
                String goodsSn = getCellString(row, 1);
                //商品名称
                String goodsName = getCellString(row, 2);
                QueryWrapper<ErpGoods> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("goods_sn",goodsSn);
                List<ErpGoods> goodss = erpGoodMapper.selectList(queryWrapper);
                if (goodss.size()>0){
                    return ResultUtil.error(goodsName+"商品的条码已存在");
                }
                //品牌
                String brandId = getCellString(row, 3);
                //库存
                String goodsNumber = getCellString(row, 4);
                //市场价零售
                String marketPrice = getCellString(row, 5);
                //批发价
                String shopPrice = getCellString(row, 6);
                //简称
                String goodsBrief = getCellString(row, 7);
                //产品规格
                String goodsDesc = getCellString(row, 8);
                //排序
                String sortOrder = getCellString(row, 9);
                //供应商名称
                String suppliersId = getCellString(row, 10);
                if("".equals(suppliersId)||null==suppliersId||StringUtil.isNullOrEmpty(suppliersId)){
                    return ResultUtil.error("供应商不能为空!");
                }
                //产地
                String PAddress = getCellString(row, 11);
                //厂家最小起订量
                String minimumQuantity = getCellString(row, 12);
                //单位
                String smallunitId = getCellString(row, 13);
                //门店最小起订量
                String minimumStore = getCellString(row, 14);
                //大包装规格
                String specifications = getCellString(row, 15);


                //if (erpGoodMapper.checkGoodsSnIsExist(goodsSn) == 0) {
                    //只将不重复的OrderSn添加进入Goods表
                    ErpGoods goods = new ErpGoods();
                    goods.setGoodsSn(goodsSn);
                    goods.setGoodsName(goodsName);
                    goods.setSmallunitId(getOrCreateToSmallUnit(smallunitId).getId());
                    goods.setCatId(getOrCreateCategory(catId, goods.getSmallUnitName()).getCatId());
                    goods.setBrandId(getOrCreateBrand(brandId).getBrandId());
                    goods.setGoodsNumber(Integer.valueOf(subPoint(goodsNumber)));
                    try {
                        goods.setMarketPrice(BigDecimal.valueOf(Math.abs(Double.valueOf(subPoint(marketPrice)))));
                    }catch(NumberFormatException e){
                        goods.setMarketPrice(BigDecimal.ZERO);
                    }
                    try{
                        goods.setShopPrice(BigDecimal.valueOf(Math.abs(Double.valueOf(subPoint(shopPrice)))));
                    }catch(NumberFormatException e ){
                        goods.setShopPrice(BigDecimal.ZERO);
                    }

                    goods.setGoodsBrief(goodsBrief);
                    goods.setGoodsDesc(goodsDesc);
                    goods.setSortOrder(Integer.valueOf(subPoint(sortOrder)));
                    goods.setSuppliersId(getOrCreateToSupplier(suppliersId).getSuppliersId());
                    goods.setPAddress(PAddress);
                    try {
                        goods.setMinimumQuantity(Integer.parseInt(subPoint(minimumQuantity)));
                    }catch(NumberFormatException e){
                        goods.setMinimumQuantity(1);
                    }
                    try{
                        goods.setMinimumStore(Integer.parseInt(subPoint(minimumStore)));
                    }catch(NumberFormatException e){
                        goods.setMinimumStore(1);
                    }
                    goods.setSmallunitId(getOrCreateToSmallUnit(smallunitId).getId());
                    goods.setSpecifications(specifications);

                    erpGoodMapper.insert(goods);
//                }else{
//                    throw new RuntimeException("条码重复!");
//                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(e.getMessage());
        }
        return ResultUtil.success("导入成功");
    }

    private String subPoint(String str){
        return isNumber(str.replace(",",""));
    }

    private String getCellString(Row row, int index) throws Exception{
        Cell cell = row.getCell(index);

        if(cell == null){
            return "  ";
        }

        cell.setCellType(CellType.STRING);

        return getUTF8StringFromGBKString(cell.getStringCellValue());
        //return new String(cell.getStringCellValue().getBytes("GB2312"), "UTF-8");
    }

    private String isNumber(String str){
        if(StringUtil.isNullOrEmpty(str)){
            return "0";
        }else{
            return str;
        }
    }

    private ErpCategory getOrCreateCategory(String category, String unitName) {
        QueryWrapper<ErpCategory> categoryWrapper = new QueryWrapper<>();
        categoryWrapper.eq("cat_name", category);
        List<ErpCategory> erpCategory = erpCategoryMapper.selectList(categoryWrapper);
        if (erpCategory.isEmpty()) {
            ErpCategory erpCategor = new ErpCategory();
            erpCategor.setCatName(category);
            erpCategor.setKeywords("");
            erpCategor.setCatDesc("");
            erpCategor.setParentId(0);
            erpCategor.setSortOrder(0);
            erpCategor.setTemplateFile("");
            erpCategor.setMeasureUnit(unitName);
            erpCategor.setShowInNav(1);
            erpCategor.setGrade(0);
            erpCategor.setFilterAttr("");
            erpCategor.setStyle("");
            erpCategoryMapper.insert(erpCategor);
            return erpCategor;
        }else if(erpCategory.size() != 1){
            throw new RuntimeException(category + " 该分类存在多个，对应商品请手动添加!");
        }
        return erpCategory.get(0);
    }


    private Brand getOrCreateBrand(String brandName) {
        QueryWrapper<Brand> brandWrapper = new QueryWrapper<>();
        brandWrapper.eq("brand_name", brandName);
        Brand brand = brandMapper.selectOne(brandWrapper);
        if (brand == null) {
            brand = new Brand();
            brand.setBrandName(brandName);
            brand.setBrandLogo("");
            brand.setBrandDesc("");
            brand.setSiteUrl("");
            brand.setSortOrder(0);
            brand.setIsShow(1);
            brandMapper.insert(brand);
        }
        return brand;
    }

    private SmallUnit getOrCreateToSmallUnit(String unitName) {
        QueryWrapper<SmallUnit> unitWrapper = new QueryWrapper<>();
        unitWrapper.eq("name", unitName);
        SmallUnit smallUnit = smallUnitMapper.selectOne(unitWrapper);
        if (smallUnit == null) {
            smallUnit = new SmallUnit();
            smallUnit.setName(unitName);
            smallUnitMapper.insert(smallUnit);
        }
        return smallUnit;
    }


    private Supplier getOrCreateToSupplier(String supplierName) {
        if ("".equals(supplierName)||null==supplierName){
            throw new RuntimeException("供应商不能为空!");
        }
        QueryWrapper<Supplier> supplierWrapper = new QueryWrapper<>();
        supplierWrapper.eq("suppliers_name", supplierName);
        Supplier supplier = supplierMapper.selectOne(supplierWrapper);
        if (supplier == null) {
    //        throw new RuntimeException("供应商不能为空!");
            supplier = new Supplier();
            supplier.setSuppliersName(supplierName);
            supplier.setSuppliersDesc(supplierName);
            supplier.setIsCheck(1);
            supplier.setCentralizedPurchasing(0);
            supplierMapper.insert(supplier);
            supplier = supplierMapper.selectOne(supplierWrapper);
        }
        return supplier;

    }


    public static String getUTF8StringFromGBKString(String gbkStr) {
        try {
            return new String(getUTF8BytesFromGBKString(gbkStr), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new InternalError();
        }
    }

    public static byte[] getUTF8BytesFromGBKString(String gbkStr) {
        int n = gbkStr.length();
        byte[] utfBytes = new byte[3 * n];
        int k = 0;
        for (int i = 0; i < n; i++) {
            int m = gbkStr.charAt(i);
            if (m < 128 && m >= 0) {
                utfBytes[k++] = (byte) m;
                continue;
            }
            utfBytes[k++] = (byte) (0xe0 | (m >> 12));
            utfBytes[k++] = (byte) (0x80 | ((m >> 6) & 0x3f));
            utfBytes[k++] = (byte) (0x80 | (m & 0x3f));
        }
        if (k < utfBytes.length) {
            byte[] tmp = new byte[k];
            System.arraycopy(utfBytes, 0, tmp, 0, k);
            return tmp;
        }
        return utfBytes;
    }
}
